package main

import (
	"net/http"
	"log"
	"fmt"
	"os"
	"io"
	"io/ioutil"
)

const (
	uploadPath = "./Files/"
)

func main() {
	println("http dir:" + http.Dir("."))
	http.HandleFunc("/upload", uploadHandle)
	http.HandleFunc("/uploadForm", uploadFormHandle)
	fs := http.FileServer(http.Dir(uploadPath))
	http.Handle("/Files/", http.StripPrefix("/Files/", fs))
	port := "8838"
	println("listening " + port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}
func uploadFormHandle(responseWriter http.ResponseWriter, request *http.Request) {
	responseWriter.Header().Set("Content-Type", "text/html")
	bytes, err := ioutil.ReadFile("./view/upload.html")
	if err != nil {
		fmt.Print(err)
		return
	}
	io.WriteString(responseWriter, string(bytes))
}

func uploadHandle(responseWriter http.ResponseWriter, request *http.Request) {
	file, head, err := request.FormFile("file")
	defer file.Close() //使用defer定义了函数退出时,文件关闭处理
	if err != nil {
		fmt.Println(err)
		return
	}

	filePath := uploadPath + head.Filename
	fw, err := os.Create(filePath)
	defer fw.Close()
	if err != nil {
		fmt.Println(err)
		return
	}

	_, err = io.Copy(fw, file) // := 与 = 区别: 前者用于第一次赋值, 后者用于非第一次赋值
	if err != nil {
		fmt.Println(err)
		return
	}
	io.WriteString(responseWriter, ""+filePath)

}
